/**
 * 
 */
package com.ekingstar.framework.service.impl;

import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.hibernate.Hibernate;
import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.transform.Transformers;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.dao.DataAccessException;
import org.springframework.orm.hibernate3.HibernateCallback;
import org.springframework.orm.hibernate3.HibernateTemplate;
import org.springframework.security.GrantedAuthority;
import org.springframework.security.GrantedAuthorityImpl;
import org.springframework.security.providers.dao.SaltSource;
import org.springframework.security.providers.encoding.PasswordEncoder;
import org.springframework.security.userdetails.UserDetails;
import org.springframework.security.userdetails.UsernameNotFoundException;
import org.ekingstar.utils.SysArgUtil;

import com.ekingstar.framework.app.ApplicationParameter;
import com.ekingstar.framework.dataright.DataRightConverters;
import com.ekingstar.framework.dataright.IDataRightConverter;
import com.ekingstar.framework.dataright.RowDataRightLevel;
import com.ekingstar.framework.domain.Favorites;
import com.ekingstar.framework.domain.Function;
import com.ekingstar.framework.domain.LastFunction;
import com.ekingstar.framework.domain.Person;
import com.ekingstar.framework.domain.Role;
import com.ekingstar.framework.domain.SystemParameter;
import com.ekingstar.framework.domain.User;
import com.ekingstar.framework.domain.UserRole;
import com.ekingstar.framework.security.UserUtil;
import com.ekingstar.framework.service.ISystemParameterService;
import com.ekingstar.framework.service.IUserRoleService;
import com.ekingstar.framework.service.IUserService;
import com.ekingstar.framework.service.PwdErrorAuthenticationException;
import com.ekingstar.framework.service.UserExistException;
import com.ekingstar.framework.util.HibernateCallbackUtil;
import com.ekingstar.framework.util.Page;
import com.ekingstar.framework.util.Utility;

/**
 * 
 *
 */
public class UserServiceImpl implements IUserService {
	private static SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd");
	private static Logger log = LoggerFactory.getLogger(UserServiceImpl.class);
	private HibernateTemplate hibernateTemplate;
	private ISystemParameterService systemParameterService;
	public void setSystemParameterService(
			ISystemParameterService systemParameterService) {
		this.systemParameterService = systemParameterService;
	}

	private IUserRoleService userRoleService;
	public void setUserRoleService(IUserRoleService userRoleService) {
		this.userRoleService = userRoleService;
	}

	public void setHibernateTemplate(HibernateTemplate hibernateTemplate) {
		this.hibernateTemplate = hibernateTemplate;
	}
	private SaltSource saltSource;
	private PasswordEncoder passwordEncoder;
	public void setSaltSource(SaltSource saltSource) {
		this.saltSource = saltSource;
	}

	public void setPasswordEncoder(PasswordEncoder passwordEncoder) {
		this.passwordEncoder = passwordEncoder;
	}

	/* (non-Javadoc)
	 * @see com.ekingstar.framework.service.IUserService#addUser(com.ekingstar.framework.domain.User)
	 */
	public boolean addUser(User user) {
		// TODO Auto-generated method stub
		checkExistUser(user.getName());
		User u = UserUtil.getCurrentUser();
		user.setAdderId(u.getId()==null?u.getName():u.getId());
		user.setAddDate(new Date());
		//
		Person ui = user.getUserInfo();
		if (ui != null){
			String uiId = (String)hibernateTemplate.save(ui);
			user.setUserInfoId(uiId);
		}
		hibernateTemplate.save(user);
		//
		user.setPwd(passwordEncoder.encodePassword(user.getPwd(), saltSource.getSalt(user)));
		//
		hibernateTemplate.update(user);
		UserRole ur = new UserRole();
		ur.setTUser(user);
		List list = this.hibernateTemplate.findByNamedParam("from Role a where a.deleteDate is null and a.name = :rolename" ,"rolename","ROLE_PUBLIC");
		Role r = null;
		if(!(list.size() == 0)){
			r = (Role)list.get(0);
		}else{
			r = new Role();
			r.setName("ROLE_PUBLIC");
			r.setDetail("公共角色");
			r.setAddDate(new Date());
			r.setAdderId(user.getId());
			this.hibernateTemplate.save(r);
		}
		ur.setTRole(r);
		ur.setAddDate(new Date());
		ur.setAdderId(user.getId());
		ur.setCanUse(true);
		//
		this.hibernateTemplate.save(ur);
		return false;
	}

	/* (non-Javadoc)
	 * @see com.ekingstar.framework.service.IUserService#deleteUser(java.lang.String)
	 */
	public boolean deleteUser(String id) {
		// TODO Auto-generated method stub
		User user = UserUtil.getCurrentUser();
		User u = (User)hibernateTemplate.get(User.class, id);
		u.setDeleteDate(new Date());
		u.setDeleterId(user.getId()==null?user.getName():user.getId());
		this.hibernateTemplate.save(u);
		return false;
	}

	/* (non-Javadoc)
	 * @see com.ekingstar.framework.service.IUserService#updateUser(com.ekingstar.framework.domain.User)
	 */
	public boolean updateUser(User user) {
		// TODO Auto-generated method stub
		if (user == null || user.getId() == null)  return false;
		User u = (User)hibernateTemplate.get(User.class, user.getId().trim());
		
		if (!user.getName().trim().equals(u.getName())){
			checkExistUser(user.getName());
			u.setName(user.getName());
		}
		String uiId = u.getUserInfoId();
		if (uiId != null && !uiId.trim().equals("")){
			Person ui = (Person)hibernateTemplate.get(Person.class, uiId.trim());
			hibernateTemplate.delete(ui);
		}
		if (user.getUserInfo() != null){
			Person userInfo = user.getUserInfo();
			uiId = (String)hibernateTemplate.save(userInfo);
			
			u.setUserInfoId(uiId);
			
		}
		User thisuser = UserUtil.getCurrentUser();
		u.setUpdaterId(thisuser.getId()==null?thisuser.getName():thisuser.getId());
		u.setLastUpdateDate(new Date());
		u.setUserType(user.getUserType());
		u.setName(user.getName());
		u.setPwd(passwordEncoder.encodePassword(user.getPwd(), saltSource.getSalt(user)));
		u.setPwdErrorCount(0);
		u.setEmail(user.getEmail());
		u.setEnabled(user.isEnabled());
		u.setLocked(user.getLocked());
		u.setExipred(user.getExipred());
		u.setPasswordexipred(user.getPasswordexipred());
		hibernateTemplate.save(u);
		return false;
	}

	/* (non-Javadoc)
	 * @see org.springframework.security.userdetails.UserDetailsService#loadUserByUsername(java.lang.String)
	 */
	public UserDetails loadUserByUsername(String username)
			throws UsernameNotFoundException, DataAccessException {
		log.info(new Date()+":"+username+":登陆系统!");
		List res = hibernateTemplate.findByNamedParam("from User a where a.name=:name and a.deleteDate is null ", "name", username);
		
		if (res != null && res.size()>0){
			User user = (User)res.get(0);
			int pwdErrorCount = this.getPwdErrorCount(user.getId(), false);
			int allowErrorCount = ApplicationParameter.INSTANCE.getPwdErrorCount();
			if (allowErrorCount != -1){
				if (pwdErrorCount >= allowErrorCount){
					throw new PwdErrorAuthenticationException("当天密码次数错误次数超过"+allowErrorCount+"次");
				}
			}
			if (user.getUserInfoId() != null &&! user.getUserInfoId().trim().equals("")){
				Person ui  = (Person)hibernateTemplate.get(Person.class, user.getUserInfoId().trim());
				
				user.setUserInfo(ui);
				
			}
			
			List roles = hibernateTemplate.findByNamedParam("select a.TRole.name from UserRole a " +
					" where a.deleteDate is null and a.canUse=:canUse" +
					" and a.TRole.deleteDate is null and  a.TUser.id =:uId ",
					new String[]{"uId","canUse"}, new Object[]{user.getId(),Boolean.TRUE});
			GrantedAuthority[] gas = new GrantedAuthority[]{};
			if (roles != null && !roles.isEmpty()){
				gas = new GrantedAuthority[roles.size()];
				for (int i = 0;i < roles.size();i++){
					String name  =(String)roles.get(i);
					gas[i] = new GrantedAuthorityImpl(name);
				}
				//gas = new GrantedAuthorityImpl(roles.toArray(new String[]{}));
			}
			user.setAuthorities(gas);
			return user;
		}
		return null;
	}
	
	public List<User> getUserlist() {
		StringBuffer sb = new StringBuffer("from User");
		HibernateCallback action = HibernateCallbackUtil.getCallback(sb, null, false, Transformers.aliasToBean(User.class));
		List<User> users = (List<User>)hibernateTemplate.execute(action);
		return users;
	}
	public User viewUser(String id) {
		if (id == null || id.trim().equals("")) return null;
		User user = (User)hibernateTemplate.get(User.class, id);
		if (user.getUserInfoId() != null){
			Person ui = (Person)hibernateTemplate.get(Person.class,user.getUserInfoId());
			user.setUserInfo(ui);
		}
		//StringBuffer sb = new StringBuffer("from User u where u.id = id");
		//HibernateCallback action = HibernateCallbackUtil.getCallback(sb, null, false, Transformers.aliasToBean(User.class));
		//User user = (User)hibernateTemplate.execute(action);
		return user;
	}
	
	/**
	 * 通过登录名得到userInfo
	 * @param name
	 * @return
	 */
	public  Person getUserInfo(String name)
	{
		Person userInfo=new Person();
		String hql=" from User a where a.name = :name ";
		List<User> list=hibernateTemplate.findByNamedParam(hql, "name", name);
		if(list.size()>0)
		{
			User user = list.get(0);
		if (user.getUserInfoId() != null){
			userInfo = (Person)hibernateTemplate.get(Person.class,user.getUserInfoId());
			
		}
		}
		
		return userInfo;
	}
	
	/*public Page getUserlist(int pageNo,int pageSize){
		if (pageNo <= 0) pageNo = 1;
		StringBuffer sb = new StringBuffer("" +
				" from User a where 1 = 1 and a.deleteDate is null ");
		//Map params = new HashMap();
		HibernateCallback action = HibernateCallbackUtil.getCallbackWithPage(sb, null ,null, pageNo, pageSize);
		Page page = (Page)hibernateTemplate.execute(action);
		return page;
	}*/
	
	public Page getUserlist(User user, int pageNo, int pageSize) {
		if (pageNo <= 0) pageNo = 1;
		StringBuffer sb = new StringBuffer("" +
				" select a " +
				" from User a " +
				" where a.deleteDate is null ");
		Map params = new HashMap();
		if (user != null){
			if (user.getName() != null && !user.getName().trim().equals("")){
				sb.append(" and (a.name like :name  )");
				params.put("name", "%"+user.getName().trim()+"%");
			}
		}
		HibernateCallback action = HibernateCallbackUtil.getCallbackWithPage(sb, params, null, pageNo, pageSize);
		Page page = (Page)hibernateTemplate.execute(action);
		return page;
	}
	
	private void checkExistUser(String userName){
		if (userName == null || userName.trim().equals("")) return;
		List res = hibernateTemplate.findByNamedParam("select count(*) from User a " +
				" where a.name=:name ", "name", userName.trim()); 
		if (res != null && res.size() > 0){
			Number count = (Number)res.get(0);
			if (count.intValue() > 0) throw new UserExistException("用户名存在!");
		}
	}

	/**
	 * @exception ��֤����
	 */
	public boolean checkPassword(User user) {
		if (user.getId() == null || user.getId().equals("")) return false;
		List list = this.hibernateTemplate.findByNamedParam("select a.pwd from User a where a.id = :id" ,"id",user.getId());
		//
		String oldpwd = (String) list.get(0);
		return passwordEncoder.isPasswordValid(oldpwd,user.getPwd(), saltSource.getSalt(user));
	}

	/**
	 *修改密码
	 */
	public void changePWD(User user, String npwd) {
		if(!Utility.isEmpty(user) && !Utility.isEmpty(user.getId()) && !Utility.isEmpty(npwd)){
			final String id = user.getId();
			final String pwd = passwordEncoder.encodePassword(npwd, saltSource.getSalt(user));
			//u.setPwd(passwordEncoder.encodePassword(user.getPwd(), saltSource.getSalt(user)));
			//user.setPwd(npwd);
			//this.updateUser(user);
			this.hibernateTemplate.execute(new HibernateCallback(){
				public Object doInHibernate(Session session)
						throws HibernateException, SQLException {
					StringBuffer sb = new StringBuffer("update User a ");
					sb.append(" set a.pwd=:pwd, a.pwdErrorCount='0' where a.id=:id");
					Query qsb = session.createQuery(sb.toString());
					qsb.setString("pwd", pwd);
					qsb.setString("id", id);
					qsb.executeUpdate();
					return null;
				}
			});
		}
	}
	/**
	 * 用户修改信息
	 */
	public boolean changUserInfo(User user){
		if (user == null || user.getId() == null)  return false;
		User u = (User)hibernateTemplate.get(User.class, user.getId().trim());
		
		String uiId = u.getUserInfoId();
		if (uiId != null && !uiId.trim().equals("")){
			Person ui = (Person)hibernateTemplate.get(Person.class, uiId.trim());
			hibernateTemplate.delete(ui);
		}
		if (user.getUserInfo() != null){
			Person userInfo = user.getUserInfo();
			if (User.Type.EDU.name().equals(user.getUserType())){
			}
			uiId = (String)hibernateTemplate.save(userInfo);
			
			u.setUserInfoId(uiId);
		}
		u.setUpdaterId(u.getId());
		u.setLastUpdateDate(new Date());
		hibernateTemplate.update(u);
		return false;
	}
	
	public boolean saveUser(User user) {
		// TODO Auto-generated method stub
		
		this.hibernateTemplate.saveOrUpdate(user);
		return false;
	}

	public boolean addOrUpdateMyFavarites(final String id, final List funs) {
		// TODO Auto-generated method stub
		if (id == null || id.trim().equals("")) return false;
		hibernateTemplate.execute(new HibernateCallback(){
			public Object doInHibernate(Session session)
					throws HibernateException, SQLException {
				// TODO Auto-generated method stub
				session.createQuery(" delete from Favorites a where a.userId=:id ").setParameter("id",id).executeUpdate();
				if (funs == null || funs.isEmpty()) return null;
				Date now = new Date();
				for (int i =0;i < funs.size();i++){
					Favorites ft = new Favorites();
					Function fun = (Function)funs.get(i);
					ft.setCreateTime(now );
					ft.setUserId(id);
					ft.setFunctionId(fun.getId());
					session.save(ft);
				}
				return null;
			}
		});
		return false;
	}

	public List<Function> getLastFunctions(String id) {
		// TODO Auto-generated method stub
		if (id ==  null || id.trim().equals("")) return null;
		StringBuffer sb = new StringBuffer("select  b.id as id,b.name as name,b.addresss as addresss,b.is_leaf as leaf "+
				"   from t_last_function a,t_function b  " +
				" where a.user_id=:id and a.function_id = b.id  order by a.create_Time desc  ");
		Map params = new HashMap();
		params.put("id", id);
		Map scalars = new HashMap();
		scalars.put("id", Hibernate.STRING);
		scalars.put("name", Hibernate.STRING);
		scalars.put("addresss", Hibernate.STRING);
		scalars.put("leaf", Hibernate.BOOLEAN);
		//scalars.put("show", Hibernate.BOOLEAN);
		//scalars.put("filter", Hibernate.BOOLEAN);
		HibernateCallback action = HibernateCallbackUtil.getNativeCallback(sb, params, false, scalars, Transformers.aliasToBean(Function.class));
		List<Function> res = (List)hibernateTemplate.execute(action);
		return res;
	}

	public List<Function> getMyFavarites(String id) {
		// TODO Auto-generated method stub
		if (id ==  null || id.trim().equals("")) return null;
		List<Function> res = hibernateTemplate.findByNamedParam(" select a from Function a " +
				" where a.id in (select a.functionId from Favorites a " +
				" where a.userId=:id  ) ","id",id);
		return res;
	}

	//保证只有10条记录
	public boolean updateLastFunction(final String id, Function fun) {
		// TODO Auto-generated method stub
		if (id == null || id.trim().equals("") || fun == null || fun.getId() == null) return false;
		LastFunction lf = new LastFunction();
		lf.setUserId(id);
		lf.setFunctionId(fun.getId());
		lf.setCreateTime(new Date());
		List res = hibernateTemplate.findByNamedParam("from LastFunction a where a.userId=:id and a.functionId=:fid", 
				new String[]{"id","fid"},new Object[]{id,fun.getId()});
		if (res != null && !res.isEmpty()){
			lf = (LastFunction)res.get(0);
			lf.setCreateTime(new Date());
		}
		hibernateTemplate.save(lf);
		//
		hibernateTemplate.execute(new HibernateCallback(){
			public Object doInHibernate(Session session)
					throws HibernateException, SQLException {
				// TODO Auto-generated method stub
				List res = session.createQuery(" select a.id from LastFunction a " +
						" where a.userId=:id  order by a.createTime desc  )  " +
						"  ").setParameter("id", id).setFirstResult(0).setMaxResults(10).list();
				if (res == null || res.isEmpty()) return null;
				session.createQuery(" delete from LastFunction a where a.id not in (:ids)").setParameterList("ids", res).executeUpdate();
				return null;
			}
		});
		return true;
	}

	//返回sql
	public Object getUserRowDataRights(String userId, RowDataRightLevel level,IDataRightConverter converter) {
		// TODO Auto-generated method stub
		if (userId == null || userId.trim().equals("")) return null;
		SystemParameter.ParameterType pt = null;
		//获取行级权限数据
		if (level != null){
			switch(level){
				case University:
					pt = SystemParameter.ParameterType.University;
					break;
				case Colleage:
					pt = SystemParameter.ParameterType.Colleage;
					break;
				case Major:
					pt = SystemParameter.ParameterType.Major;
					break;
				case Class:
					pt = SystemParameter.ParameterType.Class;
					break;
			}
		}
		StringBuffer sb = new StringBuffer(" select a  " +
				"  from SystemParameter a,RoleDataRight b,UserRole c   " +
				"  where b.rightId=a.id " +
				" and b.deleteDate is null " +
				" and c.TRole.id=b.rightId and c.deleteDate is null " +
				" and c.TUser.id=:uId");
		Map params = new HashMap();
		params.put("uId", userId);
		if (pt != null){
			sb.append(" and a.type=:spt");
			params.put("spt", pt.ordinal());
		}
		List res = (List)hibernateTemplate.execute(HibernateCallbackUtil.getCallback(sb, params, false, null));
		Object val = null;
		if (converter == null){
			converter = DataRightConverters.DEFAULT;
		}
		val = converter.converterRightData(res);
		return val;
	}

	public List<User> getGrantUsers(String id, String roleId) {
		// TODO Auto-generated method stub
		if (id == null || id.trim().equals("")) return null;
		if (roleId == null || roleId.trim().equals("")) return null;
		StringBuffer sb = new StringBuffer("select a.id as id,a.name as name,c.canUse as canUse,c.canGrant as canGrant " +
				"  from User a ,Role b,UserRole c " +
				" where c.TRole.id=b.id and c.TUser.id=a.id " +
				" and c.deleteDate is null and a.deleteDate is null " +
				" and c.adderId=:id and b.id=:roleId and a.id <>:id");
		Map params = new HashMap();
		params.put("id", id);
		params.put("roleId", roleId);
		HibernateCallback action = HibernateCallbackUtil.getCallback(sb, params, false, Transformers.aliasToBean(User.class));
		List users = (List)hibernateTemplate.execute(action);
		return users;
	}

	public boolean grantMyRightToUsers(String id, String roleId, Boolean canUse,Boolean canGrant,List<User> users) {
		// TODO Auto-generated method stub
		if (id == null || id.trim().equals("")) return false;
		if (roleId == null || roleId.trim().equals("")) return false;
		if (users == null || users.isEmpty()) return false;
		Role role = new Role();
		role.setId(roleId);
		Date now = new Date();
		for (User user:users){
			UserRole ur = new UserRole();
			ur.setCanGrant(canGrant);
			ur.setCanUse(canUse);
			ur.setAdderId(id);
			ur.setTUser(user);
			ur.setTRole(role);
			ur.setAddDate(now);
			hibernateTemplate.save(ur);
		}
		return true;
	}

	public boolean invokeMyRightFromUser(String myId, String roleId,
			Boolean canUse, Boolean canGrant, String id) {
		// TODO Auto-generated method stub
		if (id == null || id.trim().equals("")) return false;
		if (roleId == null || roleId.trim().equals("")) return false;
		StringBuffer sb = new StringBuffer("update UserRole a set a.deleteDate=:now , a.deleterId=:myId" +
				"  where a.TUser.id=:uId and a.TRole.id=:rId and a.adderId=:myId ") ;
		Map params = new HashMap();
		params.put("uId", id);
		params.put("rId", roleId);
		params.put("myId", myId);
		params.put("now", new Date());
		HibernateCallback action = HibernateCallbackUtil.getCallback(sb, params, true, null);
		hibernateTemplate.execute(action);
		return true;
	}

	public boolean gengerateUsers() {
		// TODO Auto-generated method stub
		hibernateTemplate.execute(new HibernateCallback(){

			public Object doInHibernate(Session session)
					throws HibernateException, SQLException {
				// TODO Auto-generated method stub
				
				Query query = session.createSQLQuery("select name,code from DM_GX");
				Iterator it = query.list().iterator();
				//高校编码+XL+10
				int i = 0;
				List roles = new ArrayList();
				Role r = new Role();
				r.setCanGrant(Boolean.FALSE);
				r.setCanUse(Boolean.TRUE);
				r.setId("2c9081f12094b54a0120952aaeea000b");
				roles.add(r);
				while (it.hasNext()){
					i ++;
					Object[] nameCode = (Object[])it.next();
					String userAccount = nameCode[1]+"XL10";
					Query query2 = session.createQuery("from User a where a.name=:name").setParameter("name", userAccount);
					User u = (User)query2.uniqueResult();
					if (u == null){
						User user = new User();
						user.setUserType(User.Type.University_PT.name());
						user.setName(nameCode[1]+"XL10");
						user.setPwd(nameCode[1]+"XL10");
						Person ui = new Person();
						ui.setSex("1");
						ui.setName(""+nameCode[0]);
						user.setUserInfo(ui);
						UserServiceImpl.this.addUser(user);
						System.out.println("di "+i);}
					else {
						UserServiceImpl.this.userRoleService.userAddRole(u.getId(), roles);
					}
				}
				return null;
			}
			
		});
		return false;
	}

	public int getPwdErrorCount(String id, boolean isUpdate) {
		// TODO Auto-generated method stub
//		if (id == null || id.trim().equals("")) return 0;
//		Date now = new Date();
//		User user = (User)this.hibernateTemplate.get(User.class, id);
//		if (user == null) return 0;
//		Integer pwdErrorCount = user.getPwdErrorCount();
//		Date pwdErrorDate = user.getPwdErrorDate();
//		if ( !isUpdate ){
//			if (pwdErrorDate == null ) return 0;
//			if (sdf.format(pwdErrorDate).equals(sdf.format(now))){
//				return pwdErrorCount == null ? 0:pwdErrorCount.intValue();
//			}
//			else {
//				user.setPwdErrorDate(null);
//				user.setPwdErrorCount(null);
//				hibernateTemplate.save(user);
//				return 0;
//			}
//			
//		}
//		
//		if (pwdErrorDate == null){
//			pwdErrorDate = now;
//			pwdErrorCount = 1;
//		}else if (sdf.format(pwdErrorDate).equals(sdf.format(now))){
//			pwdErrorDate = now;
//			pwdErrorCount = pwdErrorCount == null? 1:(pwdErrorCount+1);
//		}
//		else{
//			pwdErrorDate = now;
//			pwdErrorCount = 1;
//		}
//		user.setPwdErrorCount(pwdErrorCount);
//		user.setPwdErrorDate(pwdErrorDate);
//		hibernateTemplate.save(user);
		return 0;
	}

	public void clearErrorCount(String id) {
		// TODO Auto-generated method stub
		if (id == null || id.trim().equals("")) return ;
		User user = (User)this.hibernateTemplate.get(User.class, id);
		if (user != null){
			user.setPwdErrorCount(null);
			user.setPwdErrorDate(null);
			hibernateTemplate.save(user);
		}
	}
	
	public Map getUserFunctionParamValues(final String userId, String funAddress) {
		// TODO Auto-generated method stub
		if (userId == null || userId.trim().equals("")) return null;
		if (funAddress == null || funAddress.trim().equals("")) return null;
		List res = hibernateTemplate.findByNamedParam(" from Function a where a.addresss=:address", "address", funAddress.trim());
		if (res == null || res.isEmpty()) return null;
		Function fun = (Function)res.get(0);
		final String funId = fun.getId();
		//获取功能的参数
		res = hibernateTemplate.findByNamedParam("select new Map(a.parameterName as paramName,a.id as id,a.parameterType as paramType) " +
				" from FunctionParameter a " +
				" where a.functionId=:fId", "fId", funId);
		if (res == null || res.isEmpty()) return null;
		//获取功能参数值
		for (int i =0 ;i < res.size();i++){
			Map temp = (Map)res.get(i);
			String paramId = (String)temp.get("id");
			Number paramType = (Number)temp.get("paramType");
			List vals = hibernateTemplate.findByNamedParam("select distinct a.paramValue " +
					" from RoleFunctionParamValue a " +
					" where a.isvalid='1' and a.paramId=:pId " +
					" and  a.roleId in (select b.TRole.id from UserRole b where b.TUser.id=:uId) ",
					 new String[]{"pId","uId"},new Object[]{paramId,userId});
			if (vals == null || vals.isEmpty()) continue;
			//转换值
			if(paramType.intValue() == 0){
				//SQL语句
				String val = (String)vals.get(0);
				
				//如果SQL中有显式定义的userId，则需要进行替换处理，此处理模式由ekingstar于20110507实施现场添加
				if(val.indexOf(SysArgUtil.SYSPARAM_USERID)!=-1){
					//计算子串数目
					int count=0;
					int ip=0;
					String splitStr = val;				
					while(ip!=-1){
					   ip=splitStr.indexOf(SysArgUtil.SYSPARAM_USERID);				   
					   splitStr=splitStr.substring(ip+SysArgUtil.SYSPARAM_USERID.length());				   
					   if(ip!=-1) count++;
					}	
					
					//替换字串
					for(int j=0;j<count;j++){						
						val= val.substring(0,val.indexOf(SysArgUtil.SYSPARAM_USERID))+userId+val.substring(val.indexOf(SysArgUtil.SYSPARAM_USERID)+SysArgUtil.SYSPARAM_USERID.length());
					}
				}else{
					//默认处理方式 在Sql语句后添加 当前登录者登录号。
					val = val+"'"+UserUtil.getCurrentUser().getUsername()+"'";
				}
				
				StringBuffer sb = new StringBuffer(val);				
				HibernateCallback action = HibernateCallbackUtil.getNativeCallback(sb, null, false, null,null);
				List list = (List)hibernateTemplate.execute(action);				
				String paramValue = "";
				for (int j = 0; j < list.size();j++){
					String bh = (String)list.get(j);
					paramValue+=bh+",";
				}		
				if(paramValue.length()>0)
					paramValue=paramValue.substring(0,paramValue.length()-1);
				else
					paramValue="none";
				
				temp.put("paramValue", new String[]{paramValue});				
				
			}else if(paramType.intValue() == 1){
				//多值
				Set paramValue = new HashSet();
				for (int j = 0; j < vals.size();j++){
					String val = (String)vals.get(j);
					String[] sval = val.split(",");
					for (int k=0;sval != null && k < sval.length;k++){
						if (sval[k] != null && sval[k].length() > 0){
							paramValue.add(sval[k]);
						}
					}
				}				
				temp.put("paramValue", paramValue.toArray(new String[0]));
			}else{
				//单值
				String val = (String)vals.get(0);
				temp.put("paramValue", new String[]{val});
			}
		}
		//转换为Map
		Map retMap = new HashMap();
		for (int i =0 ;i < res.size();i++ ){
			Map temp = (Map)res.get(i);
			String paramName = (String)temp.get("paramName");
			String[] paramValue = (String[])temp.get("paramValue");
			if (paramValue != null ){
				retMap.put(paramName, paramValue);
			}
		}
		return retMap;
	}
	
}
